require 'builder'

module ReaderHelper
    def to_relevant_hash(entry)
        {:url=>entry.string.first.content.sub(/feed\//, ''), :title=>entry.string.second.content, :folder=>entry.list.first.object.first.string.second.content}
    end

    def produce_xml(entries)
        xml = Builder::XmlMarkup.new(:indent=>2)
        xml.instruct! :xml, :version=>"1.0", :encoding=>"UTF-8"
        res=xml.opml(:version=>'1.0'){
            xml.head{
                xml.title('subscriptions')
            }
            xml.body{
                group_by_folder(entries).each{ |folder, group|
                    xml.outline(:text=>folder.to_s, :title=>folder.to_s){
                        group.each{|entry|
                            htmlUrl= entry.url.scan(/[a-z]*\:\/\/[a-z]*\.[a-z]*\.?[a-z]*/).first
                            xml.outline(:text=>entry.title, :title=>entry.title, :type=>'rss', :xmlUrl=>entry.url, :htmlUrl=>htmlUrl)
                        }
                    }
                }
            }
        }
        res
    end

    def group_by_folder(entries)
        res={}
        entries.each{|entry|
            folder = entry.folder.to_sym
            if (res.key?(folder))
                res[folder]<<entry
            else
                res[folder]=[entry]
            end
        }
        res
    end
end